import { getChannelsApi } from "@/apis/home";
import { RootState, RootThunkAction } from "@/types/store";
import { getLocalChannels, isAuth, setLocalChannels } from "@/utils/storage";
import { Action, createSlice, ThunkDispatch } from "@reduxjs/toolkit";

const HomeSlice = createSlice({
  name: "home",
  initialState: {
    channels: [],
  },
  reducers: {
    setChannels: (state, action) => {
      state.channels = action.payload;
    },
  },
});

export const { setChannels } = HomeSlice.actions;

// 获取频道列表
export const fetchChannels =
  (): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    if (isAuth()) {
      // 已登录
      const { data } = await getChannelsApi();
      dispatch(setChannels(data.data.channels));
    } else {
      // 未登录
      const cacheChannels = getLocalChannels()
      if(cacheChannels && cacheChannels.length) {
        // 有缓存
        dispatch(setChannels(cacheChannels))
      } else {
        // 无缓存
        const { data } = await getChannelsApi();
        dispatch(setChannels(data.data.channels));
        setLocalChannels(data.data.channels)
      }
    }
  };

export default HomeSlice.reducer;
